#include "stdafx.h"
#include "net/ICMPPacketImpl.hpp"

#include "filesys/process.hpp"
using JHCPP::filesys::CProcess;
#include "stdlib/timespan.hpp"
#include "stdlib/timestamp.hpp"
using JHCPP::stdlib::CTimeSpan;
using JHCPP::stdlib::CTimeStamp;
#include "stdlib/exception.hpp"
using namespace JHCPP::stdlib::jhException;
#include "utils/numberformatter.hpp"
using JHCPP::utils::CNumberFormatter;
#include <sstream>

NET_NAMESPACE_BEGIN

//
// CICMPPacketImpl
//
const UInt16 CICMPPacketImpl::MAX_PACKET_SIZE = 4096;
const UInt16 CICMPPacketImpl::MAX_SEQ_VALUE   = 65535;

CICMPPacketImpl::CICMPPacketImpl(int dataSize)
	: m_seq(0),
	m_pPacket(new UInt8[MAX_PACKET_SIZE]),
	m_dataSize(dataSize)
{
	if (m_dataSize > MAX_PACKET_SIZE)
		throw InvalidArgumentException("Packet size must be <= " + CNumberFormatter::format(MAX_PACKET_SIZE));
}

CICMPPacketImpl::~CICMPPacketImpl()
{
	delete [] m_pPacket;
}

void CICMPPacketImpl::setDataSize(int dataSize)
{
	m_dataSize = dataSize;
	initPacket();
}

int CICMPPacketImpl::getDataSize() const
{
	return m_dataSize;
}

const UInt8* CICMPPacketImpl::packet(bool init)
{
	if (init) 
		initPacket();

	return m_pPacket;
}

UInt16 CICMPPacketImpl::sequence() const
{
	return m_seq;
}

UInt16 CICMPPacketImpl::nextSequence()
{
	return ++m_seq;
}

void CICMPPacketImpl::resetSequence()
{
	m_seq = 0;
}

int CICMPPacketImpl::maxPacketSize() const
{
	return MAX_PACKET_SIZE;
}

unsigned short CICMPPacketImpl::checksum(UInt16 *addr, Int32 len)
{
	Int32 nleft = len;
	UInt16* w   = addr;
	UInt16 answer;
	Int32 sum = 0;

	while (nleft > 1)  
	{
		sum   += *w++;
		nleft -= sizeof(UInt16);
	}

	if (nleft == 1) 
	{
		UInt16 u = 0;
		*(UInt8*) (&u) = *(UInt8*) w;
		sum += u;
	}

	sum = (sum >> 16) + (sum & 0xffff);
	sum += (sum >> 16);
	answer = ~sum;
	return answer;
}


//
// CICMPv4PacketImpl
//

const UInt8 CICMPv4PacketImpl::DESTINATION_UNREACHABLE_TYPE	= 3;
const UInt8 CICMPv4PacketImpl::SOURCE_QUENCH_TYPE			= 4;
const UInt8 CICMPv4PacketImpl::REDIRECT_MESSAGE_TYPE		= 5;
const UInt8 CICMPv4PacketImpl::TIME_EXCEEDED_TYPE			= 11;
const UInt8 CICMPv4PacketImpl::PARAMETER_PROBLEM_TYPE		= 12;

const std::string CICMPv4PacketImpl::MESSAGE_TYPE[] = 
{
	"Echo Reply",
	"ICMP 1",
	"ICMP 2",
	"Dest Unreachable",
	"Source Quench",
	"Redirect",
	"ICMP 6",
	"ICMP 7",
	"Echo",
	"ICMP 9",
	"ICMP 10",
	"Time Exceeded",
	"Parameter Problem",
	"Timestamp",
	"Timestamp Reply",
	"Info Request",
	"Info Reply",
	"Unknown type"
};

const std::string CICMPv4PacketImpl::DESTINATION_UNREACHABLE_CODE[] = 
{
	"Net unreachable",
	"Host unreachable",
	"Protocol unreachable",
	"Port unreachable",
	"Fragmentation needed and DF set",
	"Source route failed",
	"Unknown code"
};

const std::string CICMPv4PacketImpl::REDIRECT_MESSAGE_CODE[] = 
{
	"Redirect datagrams for the network",
	"Redirect datagrams for the host",
	"Redirect datagrams for the type of service and network",
	"Redirect datagrams for the type of service and host",
	"Unknown code"
};

const std::string CICMPv4PacketImpl::TIME_EXCEEDED_CODE[] = 
{
	"Time to live exceeded in transit",
	"Fragment reassembly time exceeded",
	"Unknown code"
};

const std::string CICMPv4PacketImpl::PARAMETER_PROBLEM_CODE[] = 
{
	"Pointer indicates the error",
	"Unknown code"
};

CICMPv4PacketImpl::CICMPv4PacketImpl(int dataSize) : CICMPPacketImpl(dataSize), m_seq(0)
{
	initPacket();
}

CICMPv4PacketImpl::~CICMPv4PacketImpl()
{
}

int CICMPv4PacketImpl::packetSize() const
{
	return getDataSize() + sizeof(Header);
}

void CICMPv4PacketImpl::initPacket()
{
	if (m_seq >= MAX_SEQ_VALUE) 
		resetSequence();

	Header* icp = (Header*) packet(false);
	icp->type     = ECHO_REQUEST;
	icp->code     = 0;
	icp->checksum = 0;
	icp->seq      = ++ m_seq;

	icp->id       = static_cast<UInt16>(CProcess::id());

	struct timeval* ptp = (struct timeval *) (icp + 1);
	*ptp = time();

	icp->checksum = checksum((UInt16*) icp, getDataSize() + sizeof(Header));
}

struct timeval CICMPv4PacketImpl::time(UInt8* buffer, int length) const
{
	struct timeval tv;

	if (0 == buffer || 0 == length)
	{
		CTimeSpan value(CTimeStamp().epochMicroseconds());
		tv.tv_sec  = (long) value.totalSeconds();
		tv.tv_usec = (long) value.useconds();
	}
	else
	{
		struct timeval* ptv = (struct timeval*) data(buffer, length);
		if (ptv) 
			tv = *ptv;
		else 
			throw InvalidArgumentException("Invalid packet.");
	}
	return tv;
}

CICMPv4PacketImpl::Header* CICMPv4PacketImpl::header(UInt8* buffer, int length) const
{
	jh_check_ptr (buffer);

	int offset = (buffer[0] & 0x0F) * 4;
	if ((offset + (int)sizeof(Header)) > length) return 0;

	buffer += offset;
	return (Header *) buffer;
}

UInt8* CICMPv4PacketImpl::data(UInt8* buffer, int length) const
{
	return ((UInt8*) header(buffer, length)) + sizeof(Header);
}

bool CICMPv4PacketImpl::validReplyID(UInt8* buffer, int length) const
{
	Header *icp = header(buffer, length);
	return icp && (static_cast<UInt16>(CProcess::id()) == icp->id);
}

std::string CICMPv4PacketImpl::errorDescription(unsigned char* buffer, int length)
{
	Header *icp = header(buffer, length);

	if (!icp) return "Invalid header.";
	if (ECHO_REPLY == icp->type) return std::string(); // not an error

	UInt8 pointer = 0;
	if (PARAMETER_PROBLEM == icp->type)
	{
		UInt8 mask = 0x00FF;
		pointer = icp->id & mask;
	}

	MessageType type = static_cast<MessageType>(icp->type);
	int code = icp->code;
	std::ostringstream err;

	switch (type)
	{
	case DESTINATION_UNREACHABLE_TYPE:
		if (code >= NET_UNREACHABLE && code < DESTINATION_UNREACHABLE_UNKNOWN)
			err << DESTINATION_UNREACHABLE_CODE[code];
		else
			err << DESTINATION_UNREACHABLE_CODE[DESTINATION_UNREACHABLE_UNKNOWN];
		break;

	case SOURCE_QUENCH_TYPE:		
		err << "Source quench";
		break;

	case REDIRECT_MESSAGE_TYPE:
		if (code >= REDIRECT_NETWORK && code < REDIRECT_MESSAGE_UNKNOWN) 
			err << REDIRECT_MESSAGE_CODE[code];
		else
			err << REDIRECT_MESSAGE_CODE[REDIRECT_MESSAGE_UNKNOWN];
		break;

	case TIME_EXCEEDED_TYPE:
		if (code >= TIME_TO_LIVE || code < TIME_EXCEEDED_UNKNOWN)
			err << TIME_EXCEEDED_CODE[code];
		else
			err << TIME_EXCEEDED_CODE[TIME_EXCEEDED_UNKNOWN];
		break;

	case PARAMETER_PROBLEM_TYPE:
		if (POINTER_INDICATES_THE_ERROR != code)
			code = PARAMETER_PROBLEM_UNKNOWN;
		err << PARAMETER_PROBLEM_CODE[code] << ": error in octet #" << pointer;
		break;

	default:
		err << "Unknown type.";
		break;
	}

	return err.str();
}

std::string CICMPv4PacketImpl::typeDescription(int typeId)
{
	jh_assert (typeId >= ECHO_REPLY && typeId < MESSAGE_TYPE_LENGTH);

	return MESSAGE_TYPE[typeId];
}

NET_NAMESPACE_END
